#coding: utf-8

import sys
import os.path 

cur_path = os.path.dirname(__file__)
parent_path = os.path.abspath(os.path.join(cur_path, '..'))
sys.path.append(parent_path)

import time
import pymongo
import redis
from topapi import *
from exceptions import Exception
import util

def recommend(mdb, rdb, recrdb, nick):
    item_cur = mdb.items.find({'nick':nick}, fields=['title', 'has_showcase', ], timeout=False)
    item_cur.batch_size(100)
    ndays30 = util.last_n_days(30)
    for it in item_cur:
        iid = it['_id']
        str_iid = str(iid)
        n = 0
        n_rate = 0
        rate_ct = []
        for day in ndays30:
            key = str_iid + ':' + day
            n += rdb.scard(key)
#rate:iid:day:result
            key_rate = 'rate:%s:%s:good' %(str_iid, day)
            n_rate += rdb.scard(key_rate)
            rate_oid = rdb.smembers(key_rate)
            for oid in rate_oid:
                num_oid = int(oid)
                rate_of_oid = mdb.traderate.find_one({'_id':num_oid}, fields=['content', ])
                if rate_of_oid:
                    rate_ct.append(rate_of_oid['content'])
        rate_ct = rate_ct[:10]
        if it['has_showcase']:
            key = str_iid+':T'
        else:
            key = str_iid+':F'
        key_rate = 'rate:%d:good:num' %(iid)
        key_rate_ct = 'rate:%d:good:content' %(iid)
        recrdb.zadd(nick, key, n)
        print key_rate, n_rate
        recrdb.set(key_rate, n_rate)
        for rct in rate_ct:
            recrdb.rpush(key_rate_ct, rct)
    

        
    
def traverse_and_recommend(mdb, rdb, recrdb):
    skip = 0
    limit = 1000
    while True:
        cur = mdb.user.find(fields=['status', ], timeout=False).skip(skip).limit(limit)
        if cur.count(True) <= 0:
            print 'traverse finish!'
            break
        for u in cur:
            try:
                if u['status'] != 'normal':
                    print 'no normal user: %s' %(u['_id'])
                    continue
                recommend(mdb, rdb, recrdb, u['_id'])
            except Exception as e:
                raise
                print 'exception occur: %s, %s' %(repr(u['_id']), repr(e))
                continue
            print 'processed: %s' %(repr(u['_id']))
        skip += limit
    


def start():
    m = pymongo.Connection('127.0.0.1:57324')
    mdb = m.taogold
    rdb = redis.Redis(host='127.0.0.1', port=56379, db=0)
    recrdb = redis.Redis(host='127.0.0.1', port=56379, db=1)
    traverse_and_recommend(mdb, rdb, recrdb)

if __name__ == '__main__':
    start()

